/**
 * Created by Administrator on 2017/3/29.
 */
import sel from '../../index.js';
import './sun.scss';
import E from '../../direct/effect.js';
export default {
  init:function () {
    sel.app.controller('sunControll',['$scope','$http',function ($scope,$http) {
      $scope.title = '太阳系';
      $http.get('/api/tree').then(function (data) {
        $scope.data = data.data.data.data;
      });
      $scope.draw = function () {
        console.log($scope.data);
        let svgEle;
        if(sel.d3.select('svg') && sel.d3.select('svg').size() != 0){
          svgEle = sel.d3.select('svg')
        }else {
          svgEle = sel.d3.select('#sunContain').append('svg');
        }
        svgEle.html('');
       let pad = svgEle.append('g').attr('class','all');
       let zoom = sel.d3.zoom().on('zoom',()=>pad.attr('transform', sel.d3.event.transform));
       svgEle.call(zoom);
      let width = sel.d3.select('svg').style('width').replace('px',"");
      let height = sel.d3.select('svg').style('height').replace('px',"");
       let objs = sel.d3.zoomTransform(pad);
       objs.k = 1;
       objs.x = width/2;
       objs.y = height/2;
       zoom.transform(pad,objs);


       //设置星图层次
      let drawStar = function () {
        let rectNodes ={};//每个矩形的数据基础
        let rectNodeArr = [];
        let r = 20;//小圆的半径
        let padding = 200;//小圆间的间隔
        let nodeR =100;//初始化大圆的距离
        function _draw() {

        };
        _draw.arc = function(arr){
         let range =  sel.d3.scaleBand().range([0,360]);
         let arrs = [];
         for(var i = 0; i < arr.length; i++){
           arrs.push(arr[i].id)
         };
          range.domain(arrs);
         return range
        };
        _draw.degree = function(arr){
          let range =  sel.d3.scaleBand().range([0,2*Math.PI]);
          let arrs = [];
          for(var i = 0; i < arr.length; i++){
            arrs.push(arr[i].id)
          };
          range.domain(arrs);
          return range
        };
        _draw.init = function (infos,node,link) {
          _draw.defs = pad.append('defs');
          //添加箭头
          _draw.defs.append('marker')
          .attr('id', 'arrow')
          .attr('viewBox', '0 -5 10 10')
          .attr('refX', 10)
          .attr('refY', 0)
          .attr('markerWidth', 5)
          .attr('markerHeight', 5)
          .attr('orient', 'auto')
          .append('path')
          .attr('d','M0,-5L10,0L0,5')
          .attr('fill','#ccc')
          ;
          this.setNum(infos);
          this.drawNodes(node);
          this.drawLines(node,link);

        };
        _draw.setNum = function (obj) {
          let arr = [];
          for(var i = 0 ; i < obj.length;i++){
            arr.push(obj[i].ciClass.id);
            rectNodes[obj[i].ciClass.id] = [];
          };
        };
        _draw.drawNodes = function (node) {
          for(var i = 0 ; i < node.length; i++) {
            rectNodes[node[i].classId].push(node[i]);
          }
          for(var x in rectNodes ) {
            rectNodeArr.push(rectNodes[x]);
          }
          rectNodeArr.sort(function (a,b) {
            return a.length - b.length
          });
          if(rectNodeArr[0].length == 1){
            nodeR = 0;
          }
          this.rect();

        };
        _draw.rect = function () {
          for(let i = 0; i < rectNodeArr.length; i++){
            rectNodeArr[i].r = nodeR + (i * padding);
            let angle = this.arc(rectNodeArr[i]);
            let degree = this.degree(rectNodeArr[i]);
            for(let j = 0; j < rectNodeArr[i].length; j++) {
              rectNodeArr[i][j].angle = angle(rectNodeArr[i][j].id);
              rectNodeArr[i][j].degree = degree(rectNodeArr[i][j].id);
              rectNodeArr[i][j].r = rectNodeArr[i].r;
            }
          }
          _draw.circle();
        };
        _draw.circle = function () {
          let that = this;
          pad.selectAll('g.sun').data(rectNodeArr).enter().append('g').attr('class','sun');
          pad.selectAll('g.sun').each(function (d) {
            let sun = sel.d3.select(this);
            let nodeg = sun.selectAll('g.earth')
              .data(d)
              .enter()
              .append('g')
              .attr('class','earth cell')
              .on('mouseenter',function (d) {
                that.forced(d);
              })
              .on('mouseout',d=>{
                that.cancelForce();
              })
              .attr('transform',function (d) {
                d.x = Math.cos(d.degree) * d.r ;
                d.y = Math.sin(d.degree) * d.r ;
                let degree = d.angle;
                if (degree> 90 && degree < 270) {
                  degree += 180
                }
                return  "translate(" + d.x +' '+ d.y +") rotate("+degree+")";
              })
            ;
            nodeg
              .append('circle')
              .attr('r',r)
              .attr('fill',function (d) {
                return d.classColor
              })
            ;
            nodeg
            .append('text')
            .attr('text-anchor', 'middle')
            .attr('dominant-baseline', 'middle')
            .text(function (d) {
              return d.ciCode
            })
          });
        };
        _draw.drawLines = function (node,link) {



          for(var  i = 0; i < link.length; i++) {
            for(var j = 0; j < node.length;j++) {
              if(link[i].source == node[j].id ) {
                link[i].source = node[j];
              }else if(link[i].target == node[j].id ){
                link[i].target = node[j];
              }
            }
          };
          let xyS = (d)=>{
            return [
              d.x ,
              d.y
            ]
          };
          let xyT = (d)=>{
            return [
              d.x - Math.cos(d.degree) * r,
              d.y - Math.sin(d.degree) * r
            ]
          };
          let line = sel.d3.line().curve(sel.d3.curveBundle.beta(0.01));
          let middle = function (d) {
            let x1 = d.source.x;
            let x2 = d.target.x;
            let y1 = d.source.y;
            let y2 = d.target.y;
            let middleX,middleY;
            if(x1 > x2){
              middleX = (x1 - x2)/2 + x2;
            }else {
              middleX = (x2 - x1)/2 + x1;
            }
            if(y1 > y2){
              middleY = (y1 - y2)/2 + y2;
            }else {
              middleY = (y2 - y1)/2 + y1;
            }
            return [middleX,middleY];

          };
          let lineD = function(d){
            return line([xyS(d.source), middle(d), xyT(d.target)]);
          };
          pad.selectAll('.way')
          .data(link)
          .enter()
          .insert('g','g.sun')
          .attr('class','way cell')
          .append('path')
          .attr('d',function (d) {
            return lineD(d);
          })
          .attr('fill','none')
          .attr('stroke',function (d) {
            return d.source.classColor || 'blue'
          })
          .attr('marker-end', 'url(#arrow)')
          ;



        };
        _draw.forced = function (nd) {
          this.lightEffect && this.lightEffect.clear();
          //此处调用effect的时候进行参数初始化
          this.lightEffect = E.light().radius(3).speed(100).color(function (d) {
            return d.source.classColor || 'green'
          });
          sel.d3.selectAll('g.cell')
          .classed('focused',false)
          .transition('focus')
          .duration(200)
          .style('opacity','0.2')
          ;
          sel.d3.selectAll('.way path').attr('stroke-width',1);

          let name = {};
          let linesG = sel.d3.selectAll('.way').filter(function (d) {
             if(d.source.id == nd.id || d.target.id == nd.id) {
               name[d.source.id] = true;
               name[d.target.id] = true;
               return true
              }
          })
          .classed('focused',true)
          .interrupt('focus')
          .style('opacity', 1)
          ;
          //找到对应的节点
           sel.d3.selectAll('.earth')
            .filter(function (d) {
              return name[d.id]
            })
            .classed('focused',true)
            .interrupt('focus')
            .style('opacity', 1)
          ;



          linesG.selectAll('path').interrupt('focus').attr('stroke-width',3).call(this.lightEffect);
        };
        _draw.cancelForce = function () {
          this.lightEffect && this.lightEffect.clear();
          sel.d3.selectAll('.cell')
          .classed('focused', false)
          .interrupt('focus')
          .transition('focus')
          .ease(sel.d3.easeLinear)
          .style('opacity', 1)
          .selectAll('path')
          .attr('stroke-width', 1)
          ;
        }


        return _draw
      };


      let drawBegin = drawStar().init($scope.data.ciClassInfos,$scope.data.ciNodes,$scope.data.ciRltLines);





      };







    }])
  }
}